Builder Pattern 2-23
Published Date: 2020-05-24 04:32:12Z
In some cases we will have lots of args to initialize a class, this suppose to be:
- initialization with parts of args
- easily extend
- method chaining
class People:
def __init__( self, Id: int, Name: str, aChar: str = 'a'):
self.Id: int = Id
self.Name: str = Name
self.aChar: str = aChar
......
I suppose that it is a easiest example. But it has a little trouble. When we use a lots of args, it will be a terrible args' list. In next stage, try to solve "easily extend" and "long args' list".
class People:
def __init__( self,Id: int, Name: str, **kw):
self.Id: int = Id
self.Name: str = Name
self.aChar: str = kw.get("aChar","a")
self.aIntArray: List[int] = kw.get("aIntArray",[1,2,3,4,5])
......
But it cannot verify that the type is correct (or value). Of course, you can do that like self.aChar: str = kw.get("aChar","a") if type(kw.get("aChar","a")) == "int" else ...
. But it not as expected.
Go on.
class People:
class Builder:
def __init__( self, Id:int, Name: str):
self.Id: int = Id
self.Name: str = Name
self.aChar: str = "a"
self.aIntArray: List[int] = [1,2,3,4,5]
def setAChar(self,x):
if len(x) == 1: # verify the value
self.aChar = x
else:
pass # something here
def setAIntArray(self,x):
Ints = [i==int(i) for i in x]
if sum(Ints) != len(x):
pass # something here
self.aIntArray = x
def build(self):
return People(self)
def __init__( self,b: Builder):
self.Id: int = b.Id
self.Name: str = b.Name
self.aChar: str = b.aChar
self.aIntArray: List[int] = b.aIntArray
It is a good idea to use a builder class to build a class. But it use like-
p = People.build(1,"A")
p.setAChar("A")
p.setAIntArray([3,2,1])
...
I suppose that it could be simply.
...
class Builder:
def __init__( self, Id:int, Name: str):
self.Id: int = Id
self.Name: str = Name
self.aChar: str = "a"
self.aIntArray: List[int] = [1,2,3,4,5]
def setAChar(self,x):
if len(x) == 1: # verify the value
self.aChar = x
else:
pass # something here
return self
def setAIntArray(self,x):
Ints = [i==int(i) for i in x]
if sum(Ints) != len(x):
pass # something here
self.aIntArray = x
return self
def build(self):
return People(self)
...
Now, it could use like-
p1 = People.build(1,"A").setAChar("A").setAIntArray([3,2,1]).build()
p2 = People.build(1,"B").setAChar("C").build()
...
We could merge it.
class People:
class Builder:
def __init__( self, Id:int, Name: str):
self.Id: int = Id
self.Name: str = Name
self.aChar: str = "a"
self.aIntArray: List[int] = [1,2,3,4,5]
def setAChar(self,x):
if len(x) == 1: # verify the value
self.aChar = x
else:
pass # something here
return self
def setAIntArray(self,x):
Ints = [i==int(i) for i in x]
if sum(Ints) != len(x):
pass # something here
self.aIntArray = x
return self
def build(self):
return People(self)
def __init__( self,b: Builder):
self.Id: int = b.Id
self.Name: str = b.Name
self.aChar: str = b.aChar
self.aIntArray: List[int] = b.aIntArray
END.